<!--
 * @Author: your name
 * @Date: 2021-10-08 23:24:37
 * @LastEditTime: 2021-10-10 09:34:27
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue3\src\pages\watch\watchEffect\index.vue
-->
<template>
  <div>
    <h1>watchEffect</h1>
    <a-typography>
      <a-card style="margin-bottom: 30px">
        <a-typography-title>count</a-typography-title>
        <a-typography-paragraph>
          <a-input v-model:value="number1"></a-input>
          <a-input v-model:value="number2"></a-input>
        </a-typography-paragraph>
      </a-card> 

      <a-card style="margin-bottom: 30px">
        <a-typography-paragraph>
          <!-- 监听依赖 -->
          <p>监听依赖 count:{{ count }}</p>
          <p>number1&number2: {{ number1 }} -- {{ number2 }}</p>
          <a-button @click="addCount">add</a-button>
        </a-typography-paragraph>
      </a-card>

      <a-card>
        <a-typography-paragraph>
          <!-- 监听单个 -->
          <p>监听单个 count2: {{ count2 }}</p>
          <a-button @click="addCount2">add2</a-button>
        </a-typography-paragraph>
      </a-card>
      
    </a-typography>

  </div>
</template>

<script>
import { ref, reactive, toRefs, watchEffect, watch } from 'vue'
export default {
  setup(props) {
    const state = reactive({
      number1: '1',
      number2: '2',
    })
    // 监听依赖
    const count = ref(0)
    const addCount = () => {
      count.value ++
    }
    watchEffect(() => {
      console.log('count', count.value)
    }, [state.number1])

    // 设置监听单个
    const count2 = ref(2)
    const addCount2 = () => {
      count2.value ++
    }
    watch(count2, (pre, next) => { 
      console.log(count2.value, 'count2改变了' + pre)
    })

    return {
      count,
      addCount,
      count2,
      addCount2,
      ...toRefs(state)
    }
  }
}
</script>

<style>

</style>

<!--
  与watch区别：
（1）不需要手动传入依赖
（2）每次初始化时会执行一次回调函数来自动获取依赖
（3）无法获取到原值，只能得到变化后的值
-->